package com.versita.api;

import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;

import com.versita.domain.GPS;
import com.versita.domain.User;
import com.versita.domain.UserDetail;
import com.versita.domain.UserLocationHistory;
import com.versita.domain.UserLocation;
import com.versita.utils.HibernateUtil;

public class DomainAPIExtend extends DomainAPI {

    static Logger logger = Logger.getLogger(DomainAPIExtend.class);

    /**
     * TODO: make a gson format.
     * @param json
     * @return
     */
    public UserDetail register(String json) {

        return null;
    }

    public User register(User user) {
        super.create(user);
        return user;
    }

    public UserDetail register(UserDetail userDetail, UserLocation userLocation) {
        //userDetail.setUserLocation(userLocation);
        super.create(userDetail);
        return userDetail;
    }

    public long login(String username, String password) {
        List<Criterion> criteria = new LinkedList<Criterion>();
        criteria.add(Restrictions.eq("username", username));
        criteria.add(Restrictions.eq("password", password));
        List<?> list = super.read(User.class.getName(), criteria, 0, 1);
        if (list.size() == 1) {
            return ((User)list.get(0)).getUserId();
        } else {
            return -1;
        }
    }

    /**
     * 
     * @param userId
     * @param gps
     */
    public void storeUserLocationWithTime(String userId, GPS gps) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();

        session.getTransaction().begin();
        User user = (User) session.get(User.class, Long.parseLong(userId));
        if (user == null) {
            throw new RuntimeException("user not exist exception");
        } else {
            UserLocation ul = user.getUserLocation();

            if (ul == null) {
                /**
                 * If null just store the current location to the user.
                 */
                ul = new UserLocation();
                ul.setGps(gps);
                session.save(ul);

                user.setUserLocation(ul);
                session.save(user);
            } else {
                /**
                 * copy the current location to location history
                 */
                UserLocationHistory ulh = new UserLocationHistory(ul);
                session.save(ulh);

                ul.getUserLocationHistory().add(ulh);
                ul.setGps(gps);
                session.save(ul);

            }
        }
        session.getTransaction().commit();
    }
}